package com.sff.site.tree {
	
	
	import com.sff.core.sff_internal;
	import com.sff.site.connector.SwfAddressConnector;
	import com.sff.site.connector.TreeConnector;

	public class TreeConfig {

		private var _devices 		: Array;		
		public static var instance 	: TreeConfig;		
		
		/**
		 * 	<data>
				<devices>
					<device name="main" deeplink="true" default="true"/>
					<device name="pop" deeplink="true"/>
				</devices>
			</data>
		 */
		public function TreeConfig( xml : XML ) {
			_devices = new Array();
			
			_parse( xml );
			
		}
		
		public function getDefaultRootUrl() : String {
			for each (var deviceItem : DeviceItem in _devices) {
				if( deviceItem.isDefault ) {
					return deviceItem.rootUrl;
				}
			}
			return null;
		}

		public function getRootUrls() : Array {
			var arrTemp : Array = new Array();
			for each (var deviceItem : DeviceItem in _devices) {
				if( ! deviceItem.isDefault ) {
					arrTemp.push( deviceItem.rootUrl );
				}
			}
			return arrTemp;
		}
		
		public function run() : void {
			for each (var deviceItem : DeviceItem in _devices) {
				
				TreesProvider.sff_internal::createTree( deviceItem.name );
				
				if( deviceItem.isDefault ) {
					TreesProviderClass.sff_internal::MAIN_DEVICE = deviceItem.name;
				}
				
				if( deviceItem.deeplink ) {					
					SwfAddressConnector.instance.sff_internal::connectDevice( deviceItem.name );
				}
			}
		}
		
		public function addConnector( connector : TreeConnector ) : void {
			for each (var deviceItem : DeviceItem in _devices) {
				connector.sff_internal::connectDevice( deviceItem.name );
			}	
		}

		private function _parse(xml : XML) : void {
						
			var defaultDefined : Boolean = false;
			var deviceItem : DeviceItem;
			
			for each (var xmlDevice : XML in xml.devices.device) {
				deviceItem = new DeviceItem();
				deviceItem.name = xmlDevice.@name.toString();
				deviceItem.deeplink = ( String( xmlDevice.@deeplink) == "true" );
				deviceItem.isDefault = !defaultDefined && ( String( xmlDevice.@default ) == "true" );
				deviceItem.rootUrl = xmlDevice.rootUrl.text();
				
				if ( deviceItem.isDefault ) {
					defaultDefined = true;
				}
				
				_devices.push(deviceItem );
			}
			
			//if there is no device default, the default device is the first one
			if ( !defaultDefined ) {
				_devices[0].isDefault = true;
			}
		}
		
		public static function start(xml: XML ) : TreeConfig {
			if (instance == null)
				instance = new TreeConfig( xml );
			return instance;
		}		
	}
}


class DeviceItem {
	
	//name of site tree
	public var name 		: String;
	
	//is default site tree
	public var isDefault 	: Boolean = false;
	
	//using deep link or not
	public var deeplink 	: Boolean = false;
	
	//root module url
	public var rootUrl 		: String;	
}